package cn.czu.wyw.controller;

import cn.czu.wyw.annocation.LogAnnotation;
import cn.czu.wyw.pojo.Users;
import cn.czu.wyw.service.impl.ServiceA;
import cn.czu.wyw.service.impl.ServiceB;
import cn.czu.wyw.service.impl.ServiceC;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author wyw
 * @Description
 * @Date 2022/1/14 16:19
 * @Version 1.0
 */
@Api("自定义APi")
@RestController
@RequestMapping("/self")
@Slf4j
public class SelfController {

    @Autowired
    ServiceA serviceA;

    @Autowired
    ServiceB serviceB;

    @Autowired
    ServiceC serviceC;

    @Autowired
    TransactionTemplate transactionTemplate;

    @LogAnnotation
    @ApiOperation("insertUser")
    @GetMapping("/insertUser")
    public void insertUser(){
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Date now = Calendar.getInstance().getTime();
            Users users = new Users();
            users.setId("1003");
            users.setUsername("wyw");
            users.setNickname("wyw");
            users.setPassword("123");
            users.setFace("face");
            users.setCreatedTime(now);
            users.setUpdatedTime(now);
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    try {
                        serviceA.insertUser(users);
//                        serviceB.insertUser(users);
//                        serviceC.insertUser(users);
                        System.out.println("事务内");
                    }catch (Exception e){
                        transactionStatus.setRollbackOnly();
                    }

                }
            });
        }
        System.out.println("comtroller外");
    }

    @ApiOperation("spring session")
    @GetMapping("/setSession")
    @LogAnnotation
    public void setSession(HttpServletRequest httpServletRequest){
        log.info("/setSession方法执行");
    }
}
